//
//  AppDelegate.m
//  LoanOne
//
//  Created by WangZhenyu on 2017/10/5.
//  Copyright © 2017年 WangZhenyu. All rights reserved.
//

#import "AppDelegate.h"
#import "UMMobClick/MobClick.h"
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>
#import <AdSupport/AdSupport.h>
#import "WebShowViewController.h"
#import "AFNetworkReachabilityManager.h"
#import "SharedViewControllers.h"
#import "FormalOneViewController.h"
#import "ExamineOneViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "WeiboSDK.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>{
    BOOL firstStart; //启动是否进入界面
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //注册sharesdk分享
    [self registerShareSDK];
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    BOOL productionBool = YES;
#if DEBUG
    productionBool = NO;
#else
    productionBool = YES;
#endif
    [JPUSHService setupWithOption:launchOptions appKey:JPUSHKEY
                          channel:@"Publish channel"
                 apsForProduction:productionBool
            advertisingIdentifier:advertisingId];
    
    UMConfigInstance.appKey = UMKEY;
    [MobClick startWithConfigure:UMConfigInstance];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else{
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.navigationController = [[CustomNavigationController alloc] init];
    self.window.rootViewController = self.navigationController;
    
    [self startLoadingView];
    
    NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification!=nil) {
        [self performSelector:@selector(handleNotification:) withObject:remoteNotification afterDelay:1];
    }
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)startLoadingView{
    CGSize viewSize = self.window.bounds.size;
    NSString *viewOrientation = @"Portrait";    //横屏请设置成 @"Landscape"
    NSString *launchImage = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    
    float otherHeight = SCREEN_HEIGHT_DEVICE - 26 * SCREEN_SCALE;
    UIView *startView = [[UIView alloc] initWithFrame:self.window.bounds];
    UIImageView *launchView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:launchImage]];
    launchView.frame = self.window.bounds;
    launchView.contentMode = UIViewContentModeScaleAspectFill;
    [startView addSubview:launchView];
//    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
//    [activity setCenter:CGPointMake(SCREEN_WIDTH_DEVICE/2 - 90, otherHeight + 10)];
//    [activity startAnimating];
//    activity.color = ThemeColor;
//    activity.hidesWhenStopped = YES;
//    [startView addSubview:activity];
    
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, otherHeight, SCREEN_WIDTH_DEVICE, 21)];
    infoLabel.textAlignment = 1;
    infoLabel.text = @"正在为您加载配置中...";
    infoLabel.font = [UIFont systemFontOfSize:13.0f];
    infoLabel.textColor = ThemeColor;
    [startView addSubview:infoLabel];
    
    [self.navigationController.view addSubview:startView];
    //启动监听网络
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];  //开始监听
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
        if (!firstStart) {
            if (status == AFNetworkReachabilityStatusNotReachable)
            {
                NSLog(@"无网络");
//                [activity stopAnimating];
                infoLabel.text = @"请检查您的网络情况后重新打开APP";
            }else if (status == AFNetworkReachabilityStatusUnknown){
                NSLog(@"未知网络");
//                [activity stopAnimating];
                infoLabel.text = @"请检查您的网络情况后重新打开APP";
            }else if ((status == AFNetworkReachabilityStatusReachableViaWWAN)||(status == AFNetworkReachabilityStatusReachableViaWiFi)){
                NSLog(@"有网络");
                [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
                firstStart = YES;

                [[LoadConfig shareStance] loadConfigSuccess:^(NSDictionary *dic) {
                    if ([[dic objectForKey:@"verified"] isEqualToString:@"YES"]) {
                        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
                        [self.navigationController setNavigationBarStyle:YES];
                        [[LoadConfig shareStance] loadCategoriesSuccess:^(NSArray *arr) {
                            [infoLabel removeFromSuperview];
//                            [activity removeFromSuperview];
                            [UIView animateWithDuration:1.5f
                                                  delay:0.0f
                                                options:UIViewAnimationOptionBeginFromCurrentState
                                             animations:^{
                                                 startView.alpha = 0.0f;
                                                 startView.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.2, 1.2, 1);
                                             }
                                             completion:^(BOOL finished) {
                                                 [startView removeFromSuperview];
                                             }];
//                            [activity stopAnimating];
                            FormalOneViewController *viewCon = [SharedViewControllers formalOneViewCon];
                            [self.navigationController pushViewController:viewCon animated:YES];
                        } failure:^(NSString *error) {
//                            [activity stopAnimating];
                            infoLabel.text = @"请检查您的网络情况后重新打开APP";
                        }];
                    }else{
                        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
                        [self.navigationController setNavigationBarStyle:NO];
                        [infoLabel removeFromSuperview];
//                        [activity removeFromSuperview];
                        [UIView animateWithDuration:1.5f
                                              delay:0.0f
                                            options:UIViewAnimationOptionBeginFromCurrentState
                                         animations:^{
                                             startView.alpha = 0.0f;
                                             startView.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.2, 1.2, 1);
                                         }
                                         completion:^(BOOL finished) {
                                             [startView removeFromSuperview];
                                         }];
//                        [activity stopAnimating];
                        ExamineOneViewController *viewCon = [SharedViewControllers examineOneViewCon];
                        [self.navigationController pushViewController:viewCon animated:YES];
                    }

                } failure:^(NSString *error) {
//                    [activity stopAnimating];
                    infoLabel.text = @"请检查您的网络情况后重新打开APP";
                }];

            }
        }
    }];
}

- (void)registerShareSDK{
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ)]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"2452756016"
                                           appSecret:@"d76fe5d5d6f03699a8befecf8a81ac06"
                                         redirectUri:@"http://www.bawangrong.com"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx3b35bf3512f6305a"
                                       appSecret:@"36f326fc3f2364616556a4b0f711e470"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1106173689"
                                      appKey:@"vd22ohobzLkaNBQa"
                                    authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];

}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", userInfo);
}

- (void)handleNotification:(NSDictionary *)extrasDic{
    NSString *url = extrasDic[@"web"];
    if (url.length > 0) {
        WebShowViewController *viewCon = [[WebShowViewController alloc] initWithNibName:@"WebShowViewController" bundle:nil];
        viewCon.urlStr = url;
        [self.navigationController pushViewController:viewCon animated:YES];
    }
}

-(void)notificationClick:(NSNotification*)noti{
    NSDictionary *userInfo = noti.object;
    [self handleNotification:userInfo];
    
}
@end
